<template>
  <sv-page>
    <sv-nav-bar :title="pageTitle" home-icon=""></sv-nav-bar>
    <view class="exam">
      <view class="exam-container">
        <sv-exam :type="examOptions.type" :lib="examOptions.lib_id"
          :favs="myFavs" :data="examData" @changePaper="changePaper"
          @quit="onQuit"></sv-exam>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { computed, ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { examList, libList } from '@/service/api/exam'
import { useSysStore } from '@/store/sys'
import {
  favExamList,
  favExamAdd,
  favExamDelete,
  correctNumInc,
  errorNumInc,
  errorExamAdd,
  doneExamAdd
} from '@/service/api/record'
import { store } from '@/uni_modules/sv-id-pages/common/store'

const sysConfig = useSysStore().getConfig()
const navbarHeight = computed(() => {
  return sysConfig.navbarHeight + 'px'
})

const pageTitle = ref('')
const examOptions = ref({})
const libData = ref({})

// 题目列表
const examData = ref([])
const myFavs = ref([])

onLoad(async (options) => {
  examOptions.value = options
  if (!options?.lib_id) return
  await getLibById(options.lib_id)
  await handleData(options)
  todoContinue()

  examWatcher()
})

async function handleData(options) {
  // 获取对应题库lib_id的题目列表
  const examRes = await examList({
    from_lib: options.lib_id
  })
  let tempData = examRes.data || []
  if (options.type == 'exam') {
    // 打乱顺序取随机100道
    examData.value = shuffleAndPickTen(tempData, 100)
  } else {
    examData.value = tempData
  }
  console.log('==== handleData examRes :', examData.value)

  const favsRes = await favExamList({ user_id: store.userInfo._id })
  myFavs.value = favsRes.data || []
}

function todoContinue() {
  if (examOptions.value.type !== 'practice') return
  let dataCache = uni.getStorageSync('sv-exam-data-cache')
  if (dataCache[examOptions.value.lib_id]?.length > 0) {
    uni.showModal({
      title: '系统提示',
      content: '是否继续上次答题？',
      showCancel: true,
      success: ({ confirm }) => {
        if (confirm) {
          examData.value = dataCache[examOptions.value.lib_id]
        } else {
          // 重新开始答题
          uni.$emit('sv-exam-start', 0)
        }
      }
    })
  }
}

async function getLibById(lib_id) {
  if (!lib_id) return
  const libRes = await libList({ lib_id })
  libData.value = libRes.data[0]
  pageTitle.value = libData.value.lib_name
}

// 考试模式需随机打乱题库并取其中num道题目，num默认100
function shuffleAndPickTen(arr, num = 100) {
  // 打乱数组
  function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]]
    }
    return array
  }
  // 打乱后的数组取前num个（或数组长度不足num时全部）
  const shuffledArr = shuffle(arr)
  return shuffledArr.slice(0, Math.min(shuffledArr.length, num))
}

function examWatcher() {
  /**
   * 监听题目提交
   * @param e 题目记录: 可根据返回的题目记录，自定义选择存入做题记录或错题本
   */
  uni.$on('e-exam-paper-item-submit', async (e) => {
    console.log('==== 监听题目提交 e-exam-paper-item-submit :', e)
    if (e.correct) {
      // 答对
      await correctNumInc({ user_id: store.userInfo._id })
    } else {
      // 答错
      await errorNumInc({ user_id: store.userInfo._id })
      await errorExamAdd({ user_id: store.userInfo._id, exam_id: e.paper.exam_id })
    }
    await doneExamAdd({ user_id: store.userInfo._id, exam_id: e.paper.exam_id })
  })
  /**
   * 监听考完交卷
   * @param e 答题记录列表: 可根据返回的答题记录列表，缓存或上传云端，提示下一次打开是否继续上次答题
   */
  uni.$on('e-exam-paper-complete', (e) => {
    console.log('==== 监听考完交卷 e-exam-paper-complete :', e)
  })
  /**
   * 监听题目收藏
   * @param e 收藏的题目
   */
  uni.$on('e-exam-paper-item-fav', async (e) => {
    if (e.isfav) {
      // 添加收藏
      await favExamAdd({ user_id: store.userInfo._id, exam_id: e.paper.data.exam_id })
    } else {
      // 移除收藏
      await favExamDelete({ user_id: store.userInfo._id, exam_id: e.paper.data.exam_id })
    }
    // 获取新的收藏列表并更新myFavs
    const favsRes = await favExamList({ user_id: store.userInfo._id })
    console.log('==== favsRes :', favsRes.data)
    myFavs.value = favsRes.data || []
    console.log('==== 监听题目收藏 e-exam-paper-item-fav :', e)
  })
  /**
   * 监听纠错反馈
   * @param e 纠错反馈的题目
   */
  uni.$on('e-exam-paper-item-feedback', (e) => {
    console.log('==== 监听纠错反馈 e-exam-paper-item-feedback :', e)
    uni.navigateTo({
      url: '/pages/mine/feedback/feedback',
      success(res) {
        res.eventChannel.emit('e-transmit-feedback', e)
      }
    })
  })
}

/**
 * 切换题目
 * @param {Object} e 当前题目
 */
function changePaper(e) {
  console.log('==== 切换题目 :', e)
}

/**
 * 退出考试
 * @param {Object} e 做题记录，可缓存或上传云端，用作下一次打开后继续进度
 */
function onQuit(e) {
  if (examOptions.value.type == 'practice') {
    const storage = uni.getStorageSync('sv-exam-data-cache') || {}
    storage[examOptions.value.lib_id] = e
    uni.setStorageSync('sv-exam-data-cache', storage)
  }
  console.log('==== 退出考试 :', e)
}

onUnload(() => {
  // 移除事件监听
  uni.$off('e-exam-paper-item-submit')
  uni.$off('e-exam-paper-complete')
  uni.$off('e-exam-paper-item-fav')
  uni.$off('e-exam-paper-item-feedback')
})
</script>

<style lang="scss">
.exam {
  width: 100%;
  height: calc(var(--main-height-notab) - v-bind(navbarHeight));

  .exam-container {
    height: inherit;

    @include useTheme {
      background-color: getTheme('sv-background-color');
      color: getTheme('sv-text-color');
    }
  }
}
</style>